//
//  StressAlleviation.swift
//  HIextractLicve
//
//  Created by HIextractLicve on 2024/12/9.
//

import UIKit
import AVFoundation
import ProgressHUD
class StressAlleviation: UIViewController {
    private  var pickLiveCoverHTL:UIImage?
    var layerSongHTLC: AVCaptureVideoPreviewLayer?
    @IBOutlet weak var topbgVieHTl: UIView!
    var eachVioViewHTLC:THLCNOrBUTTOn?
    var mindfulnessPageHTL:THLCNPageControll?
    var journeyHTLC:UIView?
    private var  codeingcamreraSessionHTLC = AVCaptureSession()
    private var posionCamreaHTLC: AVCaptureDevice.Position = .front
    
    @IBOutlet weak var openCameraHTLCButton: UIButton!
    
    @IBOutlet weak var fanBackHTL: UIButton!
    
    @IBOutlet weak var licoverHTL: UIButton!
    
    @IBOutlet weak var rnterTitleLiveHTl: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        topbgVieHTl.layer.cornerRadius = 20
        topbgVieHTl.layer.masksToBounds = true
        licoverHTL.layer.masksToBounds = true
        var huihuo = 43
        huihuo += 1
        var pagenorHTLC = 23
        pagenorHTLC -= 2
        let community:Set<Int> = [huihuo,pagenorHTLC]
        
        if self.navigationController?.navigationBar.isHidden == true {
            journeyHTLC?.alpha = 1
            journeyHTLC?.layer.cornerRadius = 12
        }
        journeyHTLC?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)

        eachVioViewHTLC = THLCNOrBUTTOn.init()
        eachVioViewHTLC?.setTitle("anchors", for: .normal)
        if journeyHTLC != nil {
            journeyHTLC?.addSubview(eachVioViewHTLC ?? THLCNOrBUTTOn.init())
            view.addSubview(journeyHTLC!)
        }

        mindfulnessPageHTL = THLCNPageControll()
        mindfulnessPageHTL?.numberOfPages = 1
        mindfulnessPageHTL?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.tintColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.sizeToFit()

        if journeyHTLC != nil {
            journeyHTLC?.addSubview(mindfulnessPageHTL ?? THLCNPageControll.init())
           
        }

        AVAudioSession.sharedInstance().requestRecordPermission { (allowed) in
            
        }
        AVCaptureDevice.requestAccess(for: .video) { granted in
           
        }
        
        guard let cameraHTLC = cahngeCamretPOsitionHTLC(stressdescHTL: community, ocaWeozjoHTLC: posionCamreaHTLC).0,
              let cameraInputHTLC = try? AVCaptureDeviceInput(device: cameraHTLC) else { return }
        
        if codeingcamreraSessionHTLC.canAddInput(cameraInputHTLC) {
            codeingcamreraSessionHTLC.addInput(cameraInputHTLC)
        }
        
        // 设置输出
        let videoOutputHTLC = AVCaptureVideoDataOutput()
        if codeingcamreraSessionHTLC.canAddOutput(videoOutputHTLC) {
            codeingcamreraSessionHTLC.addOutput(videoOutputHTLC)
        }
        
        let mylashingLayerHTLC = AVCaptureVideoPreviewLayer(session: codeingcamreraSessionHTLC)
        mylashingLayerHTLC.frame = self.view.frame
        layerSongHTLC = mylashingLayerHTLC
         mylashingLayerHTLC.videoGravity = .resizeAspectFill
        self.view.layer.insertSublayer(mylashingLayerHTLC, below: fanBackHTL.layer)
        DispatchQueue.global(qos: .userInitiated).async { [unowned self] in
            self.codeingcamreraSessionHTLC.startRunning()
           
        }
    }

    
    

    @IBAction func Funrightnoweback(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    deinit {
        codeingcamreraSessionHTLC.stopRunning()
    }
    
    @IBAction func switcameratNowHTL(_ sender: Any) {
      
            
        codeingcamreraSessionHTLC.beginConfiguration()
        
        // 切换镜头位置
        if posionCamreaHTLC == .back {
            posionCamreaHTLC = .front
        } else {
            posionCamreaHTLC = .back
        }
        
        // 移除当前输入
        for input in codeingcamreraSessionHTLC.inputs {
            codeingcamreraSessionHTLC.removeInput(input)
        }
        
        // 添加新的输入
        var huihuo = 43
        huihuo += 1
        var pagenorHTLC = 23
        pagenorHTLC -= 2
        let community:Set<Int> = [huihuo,pagenorHTLC]
        guard let camera = cahngeCamretPOsitionHTLC(stressdescHTL: community, ocaWeozjoHTLC:posionCamreaHTLC).0,
            let cameraInput = try? AVCaptureDeviceInput(device: camera) else { return }
        if codeingcamreraSessionHTLC.canAddInput(cameraInput) {
            codeingcamreraSessionHTLC.addInput(cameraInput)
        }
        
        codeingcamreraSessionHTLC.commitConfiguration()
    }
    
    
    @IBAction func rightLiveHTL(_ sender: Any) {
        if let contetnTitle = rnterTitleLiveHTl.text  , contetnTitle.count != 0 {
            
            
            if pickLiveCoverHTL == nil {
                
                ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="),"The cover of the live title cannot be empty" , delay: 2.0)
                return
            }
            
            
            let alertINfog = """
The live streaming theme you have created requires our review.

You can turn off the camera screen and only engage in text communication with the audience!

 We will send you an approval message or rejection reason in the system notification.Please comply with relevant laws and regulations as well as our privacy policy. 

Once any violations are found, we will close your live streaming room. Thank you for your support and understanding
"""
            
            
            
            let alertv = UIAlertController(title: "Live Notice", message:alertINfog , preferredStyle: .alert)
            let scdtion = UIAlertAction(title: "Create", style: .default) { scd in
                ProgressHUD.animate("uploading......")
                
                ProgressHUD.animate("Under review.....")
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 4, execute: DispatchWorkItem(block: {
                    var huihuo = 43
                    huihuo += 1
                    var pagenorHTLC = 23
                    pagenorHTLC -= 2
                    let community:Set<Int> = [huihuo,pagenorHTLC]
                    self.navigationController?.pushViewController(SpiritualGrounding.init(stressdescHTL: community, covertLiveing: self.pickLiveCoverHTL!, themfHTLC: contetnTitle, ifopentenCamrraIsselected: self.openCameraHTLCButton.isSelected), animated: true)
                }))
                
            }
            alertv.addAction(scdtion)
            alertv.addAction(UIAlertAction(title: "Cancel", style: .default))
            self.present(alertv, animated: true)
            
        }else{
            
            ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="), "The content of the live title cannot be empty", delay: 3.0)
           
        
        }
        
    }
    
    @IBAction func changeLiveColverHTL(_ sender: UIButton) {
        
      
       
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            let photoPicker = UIImagePickerController()
            photoPicker.delegate = self
            photoPicker.allowsEditing = false
            
         
                photoPicker.sourceType = .photoLibrary
        
            
  
            self.present(photoPicker, animated: true, completion: nil)
            
        }else {
            
          
                ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("U29ycnksTm8gYWxidW0gcGVybWlzc2lvbg=="), HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="), delay: 2.0)
        
           
          
        }
    }
    
    
    func cahngeCamretPOsitionHTLC(stressdescHTL:Set<Int>,ocaWeozjoHTLC: AVCaptureDevice.Position) -> (AVCaptureDevice?,Int?,Int?) {
     
        let devices = AVCaptureDevice.DiscoverySession(
            deviceTypes: [.builtInWideAngleCamera],
            mediaType: .video,
            position: .unspecified).devices
        
        return (devices.first(where: { $0.position == ocaWeozjoHTLC }),999,999)
       
    }
    
    @IBAction func setingCloseCameraMyLiveTouchHTLC(_ sender: UIButton) {
        
        
        
        if sender.isSelected == false {//开着镜头，去关闭
            let adlkfVC = UIAlertController(title:HTLROOOMMeasg.BinrwetioBase64("Q2xvc2UgdGhlIGNhbWVyYQ==") , message: HTLROOOMMeasg.BinrwetioBase64("QWZ0ZXIgdHVybmluZyBvZmYgdGhlIGNhbWVyYSwgdGhlIGxpdmUgYnJvYWRjYXN0IHJvb20gd2lsbCBiZSB0cmFuc2Zvcm1lZCBpbnRvIGEgdGV4dCBsaXZlIGJyb2FkY2FzdCByb29tIQ=="), preferredStyle: UIAlertController.Style.alert)
            
            adlkfVC.addAction(UIAlertAction(title: HTLROOOMMeasg.BinrwetioBase64("Q29tbWVudA=="), style: .default, handler: { adlet in
                sender.isSelected = true
                self.layerSongHTLC?.isHidden = true
                self.codeingcamreraSessionHTLC.stopRunning()
            }))
            
            adlkfVC.addAction(UIAlertAction(title:HTLROOOMMeasg.BinrwetioBase64("Q2FuY2Vs"), style: .default))
            self.present(adlkfVC, animated: true)
            return
        }
        
        if sender.isSelected == true {//guan着镜头，去打开
            let adlkfVC = UIAlertController(title: HTLROOOMMeasg.BinrwetioBase64("T3BlbiB0aGUgY2FtZXJh"), message: HTLROOOMMeasg.BinrwetioBase64("QWZ0ZXIgdHVybmluZyBvbiB0aGUgY2FtZXJhLCB0aGUgbGl2ZSBicm9hZGNhc3Qgcm9vbSB3aWxsIGRpc3BsYXkgdGhlIGNvbnRlbnQgb2YgdGhlIGNhbWVyYSE="), preferredStyle: UIAlertController.Style.alert)
            
            adlkfVC.addAction(UIAlertAction(title:HTLROOOMMeasg.BinrwetioBase64("U3VyZQ==") , style: .default, handler: { adlet in
                sender.isSelected = false
                self.layerSongHTLC?.isHidden = false
                DispatchQueue.global(qos: .userInitiated).async { [unowned self] in
                   
                        self.codeingcamreraSessionHTLC.startRunning()
                    
                    
                   
                }
            }))
            
            adlkfVC.addAction(UIAlertAction(title:HTLROOOMMeasg.BinrwetioBase64("Q2FuY2Vs"), style: .default))
            self.present(adlkfVC, animated: true)
        }
      
    }
    
    
}


extension  StressAlleviation :UINavigationControllerDelegate, UIImagePickerControllerDelegate{
   
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
     
            picker.dismiss(animated: true)
        
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
      
       
        if let image : UIImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
            DispatchQueue.main.async {
                picker.dismiss(animated: true)
               
                    self.pickLiveCoverHTL = image
                    
                
                
               
                self.licoverHTL.setImage(image, for: .normal)
            }
        }
       
       
        
    }
    
    
    
}
